<template>
  <div class="hexagram-model">
    <el-card class="search-card">
      <el-form :model="searchForm" label-width="80px" inline>
        <el-form-item label="卦名">
          <el-input v-model="searchForm.name" placeholder="请输入卦名" />
        </el-form-item>
        <el-form-item label="卦象">
          <el-input v-model="searchForm.symbol" placeholder="请输入卦象" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <span>卦象管理</span>
          <div class="header-actions">
            <el-button type="primary" @click="handleAdd">新增卦象</el-button>
          </div>
        </div>
      </template>
      
      <el-table :data="hexagramList" stripe style="width: 100%" v-loading="loading">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="卦名" />
        <el-table-column prop="symbol" label="卦象" />
        <el-table-column prop="trigramUpper" label="上卦" width="100" />
        <el-table-column prop="trigramLower" label="下卦" width="100" />
        <el-table-column prop="meaning" label="基本含义" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 卦象编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      @close="handleDialogClose"
    >
      <el-form
        ref="hexagramFormRef"
        :model="hexagramForm"
        :rules="hexagramFormRules"
        label-width="100px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="卦名" prop="name">
              <el-input v-model="hexagramForm.name" placeholder="请输入卦名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="卦象" prop="symbol">
              <el-input v-model="hexagramForm.symbol" placeholder="请输入卦象" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="上卦" prop="trigramUpper">
              <el-select v-model="hexagramForm.trigramUpper" placeholder="请选择上卦" style="width: 100%">
                <el-option label="乾" value="乾" />
                <el-option label="坤" value="坤" />
                <el-option label="震" value="震" />
                <el-option label="巽" value="巽" />
                <el-option label="坎" value="坎" />
                <el-option label="离" value="离" />
                <el-option label="艮" value="艮" />
                <el-option label="兑" value="兑" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="下卦" prop="trigramLower">
              <el-select v-model="hexagramForm.trigramLower" placeholder="请选择下卦" style="width: 100%">
                <el-option label="乾" value="乾" />
                <el-option label="坤" value="坤" />
                <el-option label="震" value="震" />
                <el-option label="巽" value="巽" />
                <el-option label="坎" value="坎" />
                <el-option label="离" value="离" />
                <el-option label="艮" value="艮" />
                <el-option label="兑" value="兑" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="基本含义" prop="meaning">
          <el-input
            v-model="hexagramForm.meaning"
            type="textarea"
            :rows="3"
            placeholder="请输入基本含义"
          />
        </el-form-item>
        
        <el-form-item label="卦辞" prop="description">
          <el-input
            v-model="hexagramForm.description"
            type="textarea"
            :rows="4"
            placeholder="请输入卦辞"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSaveHexagram" :loading="saveLoading">
            保存
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useModelStore } from '@/stores'

// 使用模型store
const modelStore = useModelStore()

// 搜索表单
const searchForm = reactive({
  name: '',
  symbol: ''
})

// 分页信息
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: computed(() => modelStore.hexagramTotal)
})

// 卦象列表（从store中获取）
const hexagramList = computed(() => modelStore.hexagramList)
const loading = computed(() => modelStore.loading)

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const isEdit = ref(false)
const saveLoading = ref(false)
const hexagramFormRef = ref()

// 卦象表单
const hexagramForm = reactive({
  id: null,
  name: '',
  symbol: '',
  trigramUpper: '',
  trigramLower: '',
  meaning: '',
  description: ''
})

// 卦象表单验证规则
const hexagramFormRules = {
  name: [
    { required: true, message: '请输入卦名', trigger: 'blur' }
  ],
  symbol: [
    { required: true, message: '请输入卦象', trigger: 'blur' }
  ],
  trigramUpper: [
    { required: true, message: '请选择上卦', trigger: 'change' }
  ],
  trigramLower: [
    { required: true, message: '请选择下卦', trigger: 'change' }
  ],
  meaning: [
    { required: true, message: '请输入基本含义', trigger: 'blur' }
  ]
}

// 获取卦象列表
const fetchHexagramList = async () => {
  const params = {
    page: pagination.currentPage,
    pageSize: pagination.pageSize,
    name: searchForm.name,
    symbol: searchForm.symbol
  }
  
  try {
    await modelStore.fetchHexagramList(params)
  } catch (error) {
    ElMessage.error('获取卦象列表失败')
  }
}

// 处理搜索
const handleSearch = () => {
  pagination.currentPage = 1
  fetchHexagramList()
}

// 处理重置
const handleReset = () => {
  searchForm.name = ''
  searchForm.symbol = ''
  pagination.currentPage = 1
  fetchHexagramList()
}

// 处理新增卦象
const handleAdd = () => {
  dialogTitle.value = '新增卦象'
  isEdit.value = false
  dialogVisible.value = true
  
  // 重置表单
  hexagramForm.id = null
  hexagramForm.name = ''
  hexagramForm.symbol = ''
  hexagramForm.trigramUpper = ''
  hexagramForm.trigramLower = ''
  hexagramForm.meaning = ''
  hexagramForm.description = ''
}

// 处理编辑卦象
const handleEdit = (row) => {
  dialogTitle.value = '编辑卦象'
  isEdit.value = true
  dialogVisible.value = true
  
  // 填充表单数据
  Object.assign(hexagramForm, row)
}

// 处理保存卦象
const handleSaveHexagram = () => {
  if (!hexagramFormRef.value) return
  
  hexagramFormRef.value.validate(async (valid) => {
    if (valid) {
      saveLoading.value = true
      
      try {
        if (isEdit.value) {
          await modelStore.updateHexagram(hexagramForm.id, hexagramForm)
          ElMessage.success('更新成功')
        } else {
          await modelStore.createHexagram(hexagramForm)
          ElMessage.success('新增成功')
        }
        dialogVisible.value = false
        await fetchHexagramList()
      } catch (error) {
        ElMessage.error(isEdit.value ? '更新失败' : '新增失败')
      } finally {
        saveLoading.value = false
      }
    }
  })
}

// 处理删除卦象
const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确定要删除卦象 "${row.name}" 吗？`,
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await modelStore.deleteHexagram(row.id)
      ElMessage.success('删除成功')
      await fetchHexagramList()
    } catch (error) {
      ElMessage.error('删除失败')
    }
  }).catch(() => {
    // 用户取消删除
  })
}

// 处理对话框关闭
const handleDialogClose = () => {
  if (hexagramFormRef.value) {
    hexagramFormRef.value.resetFields()
  }
}

// 处理分页大小变化
const handleSizeChange = (val) => {
  pagination.pageSize = val
  fetchHexagramList()
}

// 处理当前页变化
const handleCurrentChange = (val) => {
  pagination.currentPage = val
  fetchHexagramList()
}

// 组件挂载后获取卦象列表
onMounted(() => {
  fetchHexagramList()
})
</script>

<style lang="scss" scoped>
.hexagram-model {
  .search-card {
    margin-bottom: 20px;
  }
  
  .table-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    
    .pagination-container {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }
}
</style>